/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-18 15:19:50
 ******************************************************************************/
package cn.cmcc.online.smsapi.sdk.util;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import cn.cmcc.online.smsapi.sdk.action.AbsSdkDoAction;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.entity.SysParamEntityManager;
import cn.cmcc.online.smsapi.sdk.dex.DexUtil;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.net.BaseHttpRunnable;
import cn.cmcc.online.smsapi.sdk.net.util.ServerUtil;
import cn.cmcc.online.smsapi.sdk.net.util.Signaturer;
import cn.cmcc.online.smsapi.sdk.queue.SdkTaskQueue;
import cn.cmcc.online.smsapi.sdk.queue.TaskInfo;
import cn.cmcc.online.smsapi.sdk.queue.util.ResourseUtil;
import cn.cmcc.online.smsapi.sdk.ui.popu.util.ViewUtil;
import cn.cmcc.online.smsapi.util.UUIDUtils;

public class DuoquUtils {

    static AbsSdkDoAction localSdkAction = null;
    public static AbsSdkDoAction sdkAction = null;
    static String TAG = "DuoquUtils";
    
    public static LogSdkDoAction logSdkDoAction = null;
    
    public static LogSdkDoAction getLogSdkDoAction(){
    	 if (logSdkDoAction != null) {
             return logSdkDoAction;
         }
    	 return null;
    }
   
    public static AbsSdkDoAction getSdkDoAction() {
        // PrintTestLogUtil.printTestLog(TAG, " sdkAction=" + sdkAction);
        if (sdkAction != null) {
            // LogManager.d(TAG, "USE Customer getSdkDoAction");
            return sdkAction;
        }
        if (localSdkAction == null) {
            localSdkAction = new AbsSdkDoAction() {

                @Override
                public void sendSms(Context context, String phoneNum,
                        String sms, int simIndex, Map<String, String> params) {
                    try {
                        Uri uri = Uri.parse("smsto:" + phoneNum);
                        Intent it = new Intent(Intent.ACTION_SENDTO, uri);
                        it.putExtra("sms_body", sms);
                        context.startActivity(it);
                    } catch (Throwable e) {
//                        e.printStackTrace();
                        LogManager.e(Constant.TAG, "sendSms: ", e);


                    }

                }

                @Override
                public void openSms(Context context, String phoneNum,
                        Map<String, String> params) {
                    // LogManager.d("DuoquUtils", "openSms: phoneNum:" +
                    // phoneNum);
                    Uri uri = Uri.parse("sms:" + phoneNum);
                    Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    context.startActivity(it);
                }

                @Override
                public String getContactName(Context context, String phoneNum) {
                    // LogManager.d("DuoquUtils", "getContactName: phoneNum:"
                    // + phoneNum);
                    return null;
                }

                @Override
                public void markAsReadForDatabase(Context context, String msgId) {
                }

                @Override
                public void deleteMsgForDatabase(Context context, String msgId) {
                }

                @Override
                public void openSmsDetail(Context context, String msgId,
                        Map extend) {
                    // TODO Auto-generated method stub

                }

            };
        }
        LogManager.d(TAG, "USE Local getSdkDoAction");
        return localSdkAction;
    }

    /**
     * 执行动作
     * 
     * @param ac
     * @param actionType
     * @param actionMap
     * @return
     */
    public static boolean doCustomAction(Activity ac, String actionType,
            HashMap<String, Object> params) {

        boolean res = false;
        try {
            if ("call".equalsIgnoreCase(actionType)) {
                String phoneNum = (String) params.get("phone");
                Object simIndex = params.get("simIndex");
                if (!StringUtils.isNull(phoneNum)) {
                    if (simIndex == null) {
                        simIndex = -1;
                    }
                    getSdkDoAction().callPhone(ac, phoneNum,
                            Integer.valueOf(simIndex.toString()));
                    res = true;
                }

            } else if ("open_sms".equalsIgnoreCase(actionType)
                    || "open_tongxunlu".equalsIgnoreCase(actionType)
                    || "reply_sms_open".equalsIgnoreCase(actionType)) {

                // 打开会话
                String phoneNum = (String) params.get("phoneNum");
                if (StringUtils.isNull(phoneNum)) {
                    phoneNum = (String) params.get("phone");
                }
                // LogManager.d("DuoquUtils", "actionType: " + actionType
                // + " phoneNum: " + phoneNum);
                if (!StringUtils.isNull(phoneNum)) {
                    String msgId = (String) params.get("msgId");
                    Map<String, String> openSmsParams = null;
                    if (!StringUtils.isNull(msgId)) {
                        openSmsParams = new HashMap<String, String>();
                        openSmsParams.put("msgId", msgId);
                    }
                    getSdkDoAction().openSms(ac, phoneNum, openSmsParams);
                } else {
//                    LogManager.d("DuoquUtils", "actionType: " + actionType
//                            + " phoneNum is null");
                }
            } else if ("send_sms".equalsIgnoreCase(actionType)) {
                String phoneNum = (String) params.get("phoneNum");
                String smsCode = (String) params.get("smsCode");

                if (!StringUtils.isNull(phoneNum)
                        && !StringUtils.isNull(smsCode)) {
                    Object simIndex = params.get("simIndex");
//                    LogManager.d("DuoquUtils", "actionType: " + actionType
//                            + " phoneNu :" + phoneNum + " simIndex: "
//                            + simIndex);
                    if (simIndex == null) {
                        simIndex = -1;
                    }
                    getSdkDoAction().sendSms(ac, phoneNum, smsCode,
                            Integer.valueOf(simIndex.toString()), null);
                    res = true;
                }
            } else if ("openApp".equalsIgnoreCase(actionType)) {

                // 打开应用,依据包名或依据网址
                String appName = String.valueOf(params.get("appName"));
                if (StringUtils.isNull(appName)) {
                    appName = String.valueOf(params.get("exthend"));
                }
                String appDownUrl = null;
                appDownUrl = String.valueOf(params.get("appDownUrl"));

                if (!StringUtils.isNull(appName)) {

                    getSdkDoAction().openAppByAppName(ac, appName, appDownUrl);
                } else {
                    String url = String.valueOf(params.get("url"));
                    if (!StringUtils.isNull(url)) {
                        getSdkDoAction().openAppByUrl(ac, url, appDownUrl);
                    }
                }
            } else if ("toService".equalsIgnoreCase(actionType)) {
                JSONObject jsObj = new JSONObject(params);
                if (jsObj.has("actionType")) {
                    actionType = jsObj.getString("actionType");
                }
                getSdkDoAction().toService(ac, actionType, jsObj);
            } else if ("download".equalsIgnoreCase(actionType)) {
                String appName = String.valueOf(params.get("appName"));
                String url = String.valueOf(params.get("url"));
                getSdkDoAction().downLoadApp(ac, appName, url, null);
            }else{
            	/*SDK-404 hewengao 20160422 start*/
                // 执行未来的未知类型
            	if(params != null){
                	JSONObject data = new JSONObject(params);
            		getSdkDoAction().exectueAction(ac, data, params);
            	}
            	/*SDK-404 hewengao 20160422 end */
            }

        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "doCustomAction: ", e);

        } finally {
            if (res) {
                try {
                    if (params != null && !params.containsKey("keepActivity")) {
                        if (ac != null && !ac.isFinishing()) {
                            ac.finish();
                        }
                    }
                } catch (Throwable e) {
//                    e.printStackTrace();
                    LogManager.e(Constant.TAG, "doCustomAction: ", e);

                }
            }
            if (params != null) {
                params.clear();
                params = null;
            }
        }
        return res;
    }

    /**
     * 执行动作
     * 
     * @param ac
     * @param actionData
     * @param actionMap
     * @return
     */
    public static boolean doAction(Activity ac, String actionData,
            Map<String, String> actionMap) {
        try {
            getSdkDoAction().doAction(ac, actionData, actionMap);
            logAction(ac, actionData, actionMap);
            return true;
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "doAction: ", e);

        }
        return false;
    }

    /**
     * 执行动作
     * 
     * @param ac
     * @param actionData
     * @param actionMap
     * @return
     */
    public static boolean doActionContext(Context ac, String actionData,
            Map<String, String> actionMap) {
        try {
            getSdkDoAction().doAction(ac, actionData, actionMap);
            logAction(ac, actionData, actionMap);
            return true;
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "doActionContext: ", e);

        }
        return false;
    }

    public static void logAction(Context ac, String actionData,
            Map<String, String> actionMap) {

        try {
            /* SDK-376 mobaohua 20160331 start */
            // 点击操作按键时，记录打点
            String type = "-1";

            JSONObject data = new JSONObject(StringUtils.decode(actionData));
            String typeID = data.optString("action_type_id");
            
            if (!StringUtils.isNull(typeID)) {
                type = typeID.trim();
            }else{
                String action = actionMap.get("action");
                if (!StringUtils.isNull(action)) {
                    type = String.valueOf(DexUtil.getActionCode(action));
                }
            }
            
            String sceneId = "";
            if (data.has("titleNo")) {
                sceneId = data.getString("titleNo");
            }

            if (StringUtils.isNull(sceneId)) {
                sceneId = "00000000";
            }

            if (!"-1".equals(type)) {
                // 记录入数据库
                SdkTaskQueue.addTask(new TaskInfo(5, "titleNo", sceneId,
                        "type", type));
            }
            DuoquUtils.getSdkDoAction().statisticAction(sceneId, type, null);
            /* SDK-376 mobaohua 20160331 end */
        } catch (Throwable e) {
            // TODO: handle Throwable
        }
    }

    public static Map<String, Object> getLogMap(Map<String, Object> valueMap) {
        Map map = new HashMap<String, Object>();
        try {
            if (valueMap != null && valueMap.containsKey("logkey")) {
                map.put("logkey", valueMap.get("logkey"));
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "getLogMap: ", e);

        }
        return map;
    }

    /* SDK-570 huangzhiqiang 20160802 start */
    public static String getCode(int type) {
        try {
            String res = null;
            switch (type) {
            case 0:
                res = FileUtils.getXCode1();
                break;
            case 1:
                res = ResourseUtil.getXCode2();
                break;
            case 2:
                res = Constant.getXCode3();
                break;
            case 3:
                res = ViewUtil.getXCode4();
                break;
            default:
                break;
            }
            return res == null ? "" : res;
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "DuoquUtils getCode error", e);
        }
        return "";
    }
    /* SDK-570 huangzhiqiang 20160802 end */
    
    public static String getXid(){
        /*SDK-552 hewengao 20160721 start*/
        return ServerUtil.getSha256Xid();
        /* SDK-552 hewengao 20160721 start */
    }
    
    public static String getPid(){
        /*SDK-602 wangxingjian 20161221 start*/
        String pValue = BaseHttpRunnable.getDeviceId(true);
        if (StringUtils.isNull(pValue)) {
            pValue = SysParamEntityManager.getStringParam(Constant.getContext(), Constant.UNIQUE_CODE);
            pValue = (pValue == null) ? "" : pValue;
        }
        /*SDK-602 wangxingjian 20161221 start*/
        return pValue;
    }
    
    /*SDK-602 wangxingjian 20160914 start*/
    public static String getAI(){
        return Signaturer.sha256Encode(UUIDUtils.getAndroidId());
    }
    
    public static String getNI(){
        return Signaturer.sha256Encode(UUIDUtils.getUniquePsuedoID());
    }
    /*SDK-602 wangxingjian 20160914 end*/
}
